<?php

namespace App\Admin\Controllers;

use App\Models\Material;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Column;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Log;
use App\Admin\Extensions\Tools\AjaxButton;

class MaterialController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('素材列表');
            $content->description('&nbsp;');

            $content->body($this->grid());

        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('添加素材');
            $content->description('&nbsp;');


            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Material::class, function (Grid $grid) {

            $grid->model()->orderBy('update_time', 'desc');

            $grid->id('ID')->sortable();
            $grid->column('type');
            $grid->column('name');
            $grid->column('media_id');
            $grid->column('filename')->display(function($filename) {
                //return env('APP_URL').'/uploads/'.$filename;
            });
            $grid->column('update_time')->display(function($time) {
                return date("Y-m-d H:i", $time);
            });

            //$grid->created_at();
            //$grid->updated_at();

            $grid->disableExport();

            // 图片（image）、视频（video）、语音 （voice）、图文（news）
            $grid->filter(function($filter){
                $filter->disableIdFilter();
                $filter->equal('MsgType')->select([
                    'image' => 'image',
                    'voice' => 'voice',
                    'video' => 'video',
                    'news' => 'news',
                ]);
            });

            $grid->tools(function ($tools) {
                $tools->append(new AjaxButton([
                    ['name' => '同步物料', 'url' => '/admin/materials/sync']
                ]));
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Material::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->select('type', '素材类型')->options([
                "image" => "image",
                "video" => "video",
                "voice" => "voice",
                //"news" => "news",
            ]);
            $form->image('filename')->uniqueName();
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');

            $form->saved(function (Form $form) {
                $app = app('wechat.official_account');
                $localpath = public_path('uploads')."/".$form->model()->filename;
                $originalName = $form->filename->getClientOriginalName();
                switch ($form->model()->type) {
                    case 'image':
                         $result = $app->material->uploadImage($localpath);
                        break;
                    case 'voice':
                        $result = $app->material->uploadVoice($localpath);
                        break;
                    case 'video':
                        $result = $app->material->uploadVideo($localpath, $originalName, '');
                        break;
                }

                if(isset($result) && isset($result['media_id'])) {
                    $form->model()->media_id = $result['media_id'];
                    $form->model()->url = $result['url'];
                    $form->model()->name = $originalName;
                    $form->model()->update_time = time();
                    $form->model()->save();
                }
            });
        });
    }

    public function sync()
    {
        $type = 'image';
        $app = app('wechat.official_account');
        $list = $app->material->list($type, 0, 10);
        if (!$list && !isset($list['total_count']) && !$list['total_count'] && !isset($list['item']) && !$list['item']) {
            return response()->json([
                'code' => -1,
                'message' => 'error'
            ]);
        } else {
            foreach ($list['item'] as $row) {
                Material::firstOrCreate(
                    ['type' => $type, 'media_id' => $row['media_id']],
                    ['name' => $row['name'], 'update_time' => $row['update_time'], 'url' => $row['url']]
                );
            }

            return response()->json([
                'code' => 0
            ]);
        }
    }
}
